#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include "user.h"

int mainMenu()
{
	int c;
	printf("\t\t\t       Hetol Management       \n");
	printf("\t\t\t******************************\n");
	printf("\t\t\t      1 : User login\n");
	printf("\t\t\t      2 : Costumer\n");
	printf("\t\t\t      0 : quit\n");
	printf("\t\t\t*******************************\n");
	printf("select:");
	scanf("%d",&c);
	getchar();
	while(c<0 || c>2)
	{
		printf("you input is wrong,please enter again!\n");
		scanf("%d",&c);
		getchar();
	}
	return c;
}

User *login_user()
{
	char userId[12];
	char password[6];
	int count = 0;
	User *pr;
	if(access("user.txt",F_OK) != 0){
		printf("user.txt is NULL,enter userId:\n");
		scanf("%s",userId);
		count++;
		while(strcmp(userId,"admin1001") != 0){
			printf("userId is wrong! enter again!(%d)\n",3-count);
			if(count++ > 2) return NULL;
			scanf("%s",userId);
		}
		count = 0;
		printf("enter userId password\n");
		scanf("%s",password);
		count++;
		while(strcmp(password,"320323") != 0){
			printf("password is wrong! enter again!(%d)\n",3-count);
			if(count++ > 2) return NULL;
			scanf("%s",password);
		}
		pr = (User*)malloc(sizeof(User));
		if(pr == NULL){
		return NULL;
		}
		strcpy(pr->userId,"admin1001");
		strcpy(pr->password,"320323");
		strcpy(pr->role,"admin");
		getchar();
		printf("please input admin name:\n");
		fgets(pr->name,8,stdin);
//		getchar();
		printf("please input admin sex:\n");
		fgets(pr->sex,3,stdin);
//		getchar();
		printf("please input admin email:\n");
		fgets(pr->email,19,stdin);
		write_user(pr);
		return pr;
	}
	else
	{
		pr = read_user();
		printf("enter userId:\n");
		scanf("%s",userId);
		count++;
		while(strcmp(userId,pr->userId) != 0){
			pr = pr->next;
			if(pr == NULL)
			{
				printf("userId is wrong! enter again!(%d)\n",3-count);
				if(count++ > 2) return NULL;
				scanf("%s",userId);
				pr = read_user();
			}
		}
		count = 0;
		printf("enter userId password\n");
		scanf("%s",password);
		count++;
		while(strcmp(password,pr->password) != 0){
			printf("password is wrong! enter again!(%d)\n",3-count);
			if(count++ > 2) return NULL;
			scanf("%s",password);
		}
		return pr;
	}
}

void entersystem(User *r)
{
	printf("user role:%s\n",r->role);
	if(strcmp(r->role,"admin") == 0)
		adminsystem(r);
	if(strcmp(r->role,"manager") == 0)
		managersystem(r);
	if(strcmp(r->role,"recept") == 0)
		receptsystem(r);
	if(strcmp(r->role,"cleaner") == 0)
		cleanersystem(r);
	else
		printf("\nrole wrong!\n");
}

int main()
{
	User *r;
	int c,loop = 1;
	while(loop)
	{
		system("clear");
		c = mainMenu();
		switch(c){
			case 1:
			r = login_user();
			if(r == NULL)
				loop = 0;
			else
				entersystem(r);
			break;
			case 2:
			costumersystem();
			break;
			case 0:loop = 0;break;
			default:
			loop = 0;
		}
	}
}